<?php
/**
 * Created by PhpStorm.
 * User: wangzhen
 * Date: 2022/2/22
 * Time: 4:05 PM
 */

 namespace App\Admin\Field;

use App\Exceptions\Arr;
use App\Models\HospitalAppointInterval;
use Dcat\Admin\Form\Field;

class VaccineIntervalWeekNum extends Field
{
    protected $view = 'admin.vaccine_interval_week_num';

    // 把用户输入的表单值转化为 string 格式保存到数据库
    protected function prepareInputValue($array)
    {
        foreach($array['num'] as $k=>$v){
            foreach($array['num'][$k] as $ik=>$iv){
                $row = ['week' => $k, 'num' => "", 'interval_id' => $ik ,'open'=>0];
                if(!is_null($iv)) {
                    $row['num'] = $iv;
                }
                if(isset($array['open'][$k][$ik])){
                    $row['open'] = 1;
                }
                if($row['num'] || $row['open']){
                    $data[] = $row;
                }
            }
        }
        return isset($data)?json_encode($data):'[]';
    }
    protected function formatFieldData($data)
    {
        $intervals = HospitalAppointInterval::query()->where('hospital_appoint_id',$data['hospital_appoint_id'])->get();
        $interval_num = json_decode($data['interval_num'],true);


        if($intervals){
            $typeText=[];
            foreach($intervals as $k=>$v){
                $typeText[$v->id]=$v->start."-".$v->end;
            }
            $weeks = [1, 2, 3, 4, 5, 6, 0];

            $row = [];
            foreach($typeText as $k=>$v){
                $row[$k]['title']=$v;
                $row[$k]['key']=$k;

                foreach($weeks as $wk=>$wv){

                    $filteredRow = Arr::collapse(array_filter($interval_num, function($where) use ($wv,$k) {
                        return $where['week'] == $wv && $where['interval_id'] == $k;
                    }));
                    $wArr[$wv]['open']=$filteredRow?$filteredRow['open']:0;
                    $wArr[$wv]['value']=$filteredRow?$filteredRow['num']:'';
                    $wArr[$wv]['key']=$wv;
                }
                $row[$k]['weeks']=$wArr;
            }
        }
        return $row;
    }
}
